package vn.appsmobi.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import vn.appsmobi.R;
import vn.appsmobi.model.AppInfo;
import vn.appsmobi.ulti.Constant;
import vn.appsmobi.ulti.LoginManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Pair;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;

public class EditCommentActivity extends BaseActivity {

	/* (non-Javadoc)
	 * @see com.cdn.allmobilestore.activity.BaseActivity#onCreate(android.os.Bundle)
	 */
	private AppInfo mAppInfo;	
	private EditText mEditText;
	private EditText mFullNameText;
	private CommentHandler mHandler;
	private HandlerThread mHandlerThread;
	private ProgressDialog mProgressDialog;
	private RatingBar mRatingBar;
	
	
	private View.OnClickListener cancelBtnClick = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			onBackPressed();
			
		}
	};
	
	
	private View.OnClickListener submitBtnClick = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			String fullname = EditCommentActivity.this.mFullNameText.getText().toString();
			String content = EditCommentActivity.this.mEditText.getText().toString();
		    int rate = (int)EditCommentActivity.this.mRatingBar.getRating();
		    if(fullname.isEmpty())
		    {
		    	Toast.makeText(EditCommentActivity.this,getString(R.string.app_comments_fullname_empty), Toast.LENGTH_SHORT).show();
		    }
		    if(content.isEmpty())
		    {
		    	Toast.makeText(EditCommentActivity.this,getString(R.string.app_comments_content_empty), Toast.LENGTH_SHORT).show();
		    }
		    else if(rate <= 0)
		    {
		    	Toast.makeText(EditCommentActivity.this,getString(R.string.app_comments_notrate), Toast.LENGTH_SHORT).show();
		    }
		    else
		    {
		    	//Pair<Pair<String,String>,Integer> pair = new Pair<Pair<String,String>,Integer>(new Pair<String,String>(fullname,content), Integer.valueOf(rate));
		    	
		    	//EditCommentActivity.this.mHandler.obtainMessage(0, pair).sendToTarget();
		    	//EditCommentActivity.this.mIsCommentSending = true;
		    	new PostCommentTask(fullname, content, rate).execute("");
		    }
			
		}
	};
	@Override
	protected void onCreate(Bundle arg0) {		
		super.onCreate(arg0);
		Intent intent = getIntent();
	    String appid = intent.getStringExtra(Constant.INTENT_EXTRA_APP_ID);
	    mAppInfo = AppInfo.get(appid);
		setEditMode(true);
		setCustomContentView(R.layout.edit_comment);
		setBarTitle(getString(R.string.app_comments_title, mAppInfo.getName()));
		setEditFirstButtonListener(cancelBtnClick);
		setEditSecondButtonListener(submitBtnClick);
		this.mRatingBar = ((RatingBar)findViewById(R.id.ratingbar));
	    this.mEditText = ((EditText)findViewById(R.id.comment_edit));
	    this.mFullNameText 	= ((EditText)findViewById(R.id.comment_fullname));
	    if(LoginManager.getManager().hasLogin())
	    	this.mFullNameText.setText(LoginManager.getManager().getAccount().getmUserName());	
	    mLogoButton.setVisibility(View.GONE);
	}

	/* (non-Javadoc)
	 * @see com.cdn.allmobilestore.activity.BaseActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	/* (non-Javadoc)
	 * @see com.cdn.allmobilestore.activity.BaseActivity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	/* (non-Javadoc)
	 * @see com.cdn.allmobilestore.activity.BaseActivity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
		        
		finish();		
	}

	
	private void uploadComment(String fullname,String content, int rate)
	{
		//Toast.makeText(EditCommentActivity.this,"content:" + content + "rate:" + rate, Toast.LENGTH_SHORT).show();
		
		// Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost(Constant.POST_COMMENT_URL);
	    httpclient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
	    try {
	        // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("fullname", fullname));
	        nameValuePairs.add(new BasicNameValuePair("content", content));
	        nameValuePairs.add(new BasicNameValuePair("appid", mAppInfo.getId()));
	        nameValuePairs.add(new BasicNameValuePair("version", mAppInfo.getVersion()));
	        nameValuePairs.add(new BasicNameValuePair("rate", String.valueOf(rate) ));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	        
	       // Toast.makeText(EditCommentActivity.this,  EntityUtils.toString(response.getEntity()), Toast.LENGTH_LONG).show();
	        
	    } catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    }
	}
	 private class CommentHandler extends Handler
	  {
	    public CommentHandler(Looper arg2)
	    {
	      super();
	    }
		public void handleMessage(Message paramMessage)
	    {
	      switch (paramMessage.what)
	      {      
		      case 0:	    	  
		    	  Pair<Pair<String,String>,Integer> localPair = (Pair<Pair<String,String>,Integer>)paramMessage.obj;
		    	  Pair<String,String> mesagePair = (Pair<String,String>)localPair.first;
		          String fullname = (String)mesagePair.first;
		          String content = (String)mesagePair.second;
		          Integer localInteger = (Integer)localPair.second;
		          
		          EditCommentActivity.this.uploadComment(fullname,content,localInteger.byteValue());
		          
		          break;
		      case 1:
		    	  EditCommentActivity.this.mHandlerThread.getLooper().quit();
	      }
	      
	    }
	  }
	 
	 
	 private class PostCommentTask extends AsyncTask<String, Void, String> {
		String fullname;		
		String content;
		int rate;
		
		/**Phong
		 * @param fullname
		 * @param content
		 * @param rate2
		 */
		public PostCommentTask(String fullname, String content, int rate2) {
			this.fullname = fullname;
			this.content = content;
			this.rate = rate2;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			EditCommentActivity.this.mProgressDialog = ProgressDialog.show(EditCommentActivity.this, "", getString(R.string.title_connecting));
		}

		@Override
	    protected String doInBackground(String... params) {
			
			uploadComment(fullname,content,rate);
			return "";
	    }      

	    @Override
	    protected void onPostExecute(String result) {    	    	
	    	EditCommentActivity.this.mProgressDialog.hide();
	    	Toast.makeText(EditCommentActivity.this, getString(R.string.comment_upload_hint), Toast.LENGTH_SHORT).show();
	    	InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
			Intent intent=new Intent();  
	  		setResult(RESULT_OK, intent);
	  		finish();
	    	//EditCommentActivity.this.onBackPressed();	    	
	    }
	}

}
